//
//  MPBViewController.m
//  wyw
//
//  Created by Xiaoshiheng_pro on 2017/2/24.
//  Copyright © 2017年 XIAO. All rights reserved.
//

typedef void(^PerformBlock)(NSURLResponse* response, NSData* data, NSError* error);

#import "MPBViewController.h"
#import "MPBViewControllerTableViewCell.h"
#import "MPModel.h"
#import "TFHpple.h"

#import "XSHPlayerView.h"


@interface MPBViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    
    CGFloat width;
    
}

#pragma mark -----播放器  相关的

//播放器
@property(nonatomic,strong)XSHPlayerView *playerView;

//离开页面时候是否在播放
@property (nonatomic, assign) BOOL isPlaying;
//是否在cell中播放
@property(nonatomic,assign)BOOL isInCell;
//是否在主界面底部播放
@property(nonatomic,assign)BOOL isBottomVideo;

//记录当前在哪一个cell上播放对应的indexPath
@property(nonatomic,strong) NSIndexPath *currentIndexPath;
//播放器在哪个cell上播放
@property(nonatomic,retain)MPBViewControllerTableViewCell *currentCell;


#pragma mark -----其他

@property (weak, nonatomic) IBOutlet UITableView *tableView;
/// 连接
@property (nonatomic, strong) NSString* url;
@property (nonatomic, strong) NSMutableArray* arrayItemModel;
/**
 *  下拉刷新
 */
@property (nonatomic, strong) MJRefreshNormalHeader* headerLoad;
/**
 *  下拉刷新
 */
@property (nonatomic, strong) MJRefreshBackNormalFooter* footerLoad;
/**
 *  页码
 */
@property (nonatomic, assign) NSInteger pageNumber;

@end

@implementation MPBViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    width = 100 * 16 / 9.0;
    
    self.isInCell = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    
    ///设置 其他参数
    self.url = @"http://newapi.meipai.com/output/channels_topics_timeline.json";
    self.arrayItemModel = [NSMutableArray arrayWithCapacity:0];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //  支持自适应 cell
    self.tableView.estimatedRowHeight = 260;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    
    self.headerLoad = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(upDateS)];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    //self.headerLoad.autoChangeAlpha = YES;
    // 设置header
    self.tableView.header = self.headerLoad;
    
    self.footerLoad = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upDateX)];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    //self.footerLoad.autoChangeAlpha = YES;
    // 设置header
    self.tableView.footer = self.footerLoad;
    

    
    
    [self upDateS];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
//    self.navigationController.navigationBarHidden = YES;
    if (self.playerView) {
        [self.playerView setNeedsLayout];
    }
    //从第三界面返回的时候
    if (self.navigationController.viewControllers.count == 2 && self.playerView && self.isPlaying) {
        self.isPlaying = NO;
        [self.playerView play];
    }
    
    //获取设备旋转方向的通知,即使关闭了自动旋转,一样可以监测到设备的旋转方向
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    //旋转屏幕通知
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onDeviceOrientationChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
//    self.navigationController.navigationBarHidden = NO;
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
//    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    //push到下一界面,如果当前处于播放状态，要设置为暂停
    if (self.navigationController.viewControllers.count == 3 && self.playerView && !self.playerView.isPauseByUser) {
        self.isPlaying = YES;
        [self.playerView pause];
    }
    
    self.isPlaying = YES;
    [self.playerView pause];
    
    
    //注意调用这一句
    [self.playerView resetPlayer];
}

#pragma mark -----
- (void)upDateS
{
    self.pageNumber = 1;
//    count     可不传	int	单页返回的记录条数，默认为 20，最多 100。
//    page      可不传	int	返回结果的页码，默认为1。
//    feature	可不传	string	排序方式，new 表示最新，hot 表示最热，频道默认为最新，话题默认为最热
//    max_id	可不传	int	若取最新，需传此字段，为当前分页最后一个美拍的 ID，用于获取下一页时定位
    //    http://newapi.meipai.com/output/channels_topics_timeline.json?count=20\u0026feature=\u0026id=1\u0026max_id=\u0026page=1
    
     NSString* url = [NSString stringWithFormat:@"%@?id=%@&page=%zi&count=20", self.url,self.url_id,self.pageNumber];
    
//    [self dateS:url];
    
    [self request:url PerformBlock:^(NSURLResponse* response, NSData* data, NSError* error){
        
        NSArray* json = [NSJSONSerialization
                         JSONObjectWithData:data
                         options:kNilOptions
                         error:&error];
        
        [self.arrayItemModel removeAllObjects];
        [self.arrayItemModel addObjectsFromArray:json];
        
        
        [self.headerLoad endRefreshing];
        
        if ([self.arrayItemModel count] > 0) {
            
            [self.tableView reloadData];
        }
    
    }];
}
- (void)upDateX
{
    
    self.pageNumber++;
    NSString* url = [NSString stringWithFormat:@"%@?id=%@&page=%zi&count=20", self.url,self.url_id,self.pageNumber];
    [self request:url PerformBlock:^(NSURLResponse* response, NSData* data, NSError* error){
        
        NSArray* json = [NSJSONSerialization
                         JSONObjectWithData:data
                         options:kNilOptions
                         error:&error];
        
        
        NSMutableArray* arrayItemModel = [[NSMutableArray alloc] initWithCapacity:0];
        [arrayItemModel addObjectsFromArray:json];
        
        if ([arrayItemModel count] > 0) {
            
            [self.footerLoad endRefreshing];
            
            [self.arrayItemModel addObjectsFromArray:arrayItemModel];
            
            [self.tableView reloadData];
        }
        else {
            
            self.footerLoad.arrowView.image = nil;
            [self.footerLoad noticeNoMoreData];
        }
        
    }];

}

- (void)ParsingVideoAddress:(NSString*)videoUrl  Block:(void(^)(NSString *videoUrl))block{
    
//    http://www.flvcd.com/parse.php?format=&kw=http://www.meipai.com/media/668933615
    NSString* url = [NSString stringWithFormat:@"http://www.flvcd.com/parse.php?format=&kw=%@",videoUrl];
    [self request:url PerformBlock:^(NSURLResponse* response, NSData* data, NSError* error){
    
        TFHpple* doc = [[TFHpple alloc] initWithHTMLData:data];
        TFHppleElement *element =  [doc peekAtSearchWithXPathQuery:@"//a[@class='link']"];
//        NSArray* elements = [doc searchWithXPathQuery:@"//a[@class='link']"];
        NSLog(@"%@",[element objectForKey:@"href"]);
        
        NSString *url = [element objectForKey:@"href"];
        
        block(url);
        
    
    }];
    
}

- (void)request:(NSString*)url PerformBlock:(PerformBlock)block{
    
    NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) {
        
        block(response,data,error);
        
    }];

}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [self.arrayItemModel count];
}


 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     
     MPBViewControllerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MPBCell" forIndexPath:indexPath];
     
     
     MPModel *model = [MPModel mj_objectWithKeyValues:self.arrayItemModel[indexPath.row]];
     
     cell.title.text = model.caption;
     [cell.cover_picImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_pic]];
     
     [cell.playBtn addTarget:self action:@selector(startPlayVideo:) forControlEvents:UIControlEventTouchUpInside];
     cell.playBtn.tag = indexPath.row;
     
     
     //解决复用相关问题，上下滚动视频消失，这里可以不考虑
     if (_playerView && _playerView.superview) {
         if (indexPath.row== _currentIndexPath.row) {
             [cell.playBtn.superview sendSubviewToBack:cell.playBtn];
         }else{
             [cell.playBtn.superview bringSubviewToFront:cell.playBtn];
         }
         NSArray *indexpaths = [tableView indexPathsForVisibleRows];
         
         if (![indexpaths containsObject:_currentIndexPath]) {//复用
             if ([[UIApplication sharedApplication].keyWindow.subviews containsObject:_playerView]) {
                 _playerView.hidden = NO;
             }else{
                 _playerView.hidden = YES;
             }
         }else{
             if ([cell.cover_picImageView.subviews containsObject:_playerView]) {
                 [cell.cover_picImageView addSubview:_playerView];
                 [_playerView play];
                 _playerView.hidden = NO;
             }
         }
     }
     
 
  
 
     return cell;
 }

#pragma mark   播放器 相关 的
#pragma mark - cell上播放按钮点击事件

- (void)PlayVideo:(UIButton *)sender VideoUrl:(NSString*)videoUrl{
    
    _currentIndexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
    //根据cell上的播放按钮获取到当前cell
    if ([UIDevice currentDevice].systemVersion.floatValue>=8||[UIDevice currentDevice].systemVersion.floatValue<7) {
        self.currentCell = (MPBViewControllerTableViewCell *)sender.superview.superview.superview;
    }else{//ios7系统 UITableViewCell上多了一个层级UITableViewCellScrollView
        self.currentCell = (MPBViewControllerTableViewCell *)sender.superview.superview.superview.subviews;
    }
    
    //设置播放器的显示相关
    _playerView = [XSHPlayerView sharedPlayerView];
    [self.currentCell.cover_picImageView addSubview:self.playerView];
    self.playerView.frame = self.currentCell.cover_picImageView.bounds;
    _playerView.transform = CGAffineTransformIdentity;
    [_playerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.currentCell.cover_picImageView).with.offset(0);
        make.left.equalTo(self.currentCell.cover_picImageView).with.offset(0);
        make.right.equalTo(self.currentCell.cover_picImageView).with.offset(0);
        make.height.equalTo(@(self.currentCell.cover_picImageView.frame.size.height));
        
    }];
    
    //    [_playerView.controlView addSubview:_playerView.controlView.activity];
    //    [_playerView.controlView.activity mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.center.equalTo(_playerView.controlView);
    //    }];
    
    [self.currentCell.cover_picImageView bringSubviewToFront:self.playerView];
    [self.currentCell.playBtn.superview sendSubviewToBack:self.currentCell.playBtn];
    [self.tableView reloadData];
    
    //每次播放另外一个视频之前要调用该方法，最好放在播放参数和开始播放之前
    [self.playerView resetToPlayNewURL];
    
    //*****************设置播放器相关*****************
    //必须要设置的参数
    self.playerView.isCellVideo = YES;
    //设置播放器的videoUrl
    //    B_Model *model = self.dataSource[_currentIndexPath.row];

    NSURL *url = [NSURL URLWithString:videoUrl];
    self.playerView.videoURL = url;
    self.playerView.playerLayerGravity = XSHPlayerLayerGravityResize;
    self.playerView.placeholderImageName = @"image2.png";
    //设置自动播放
    [self.playerView autoPlayTheVideo];
    
    
    //注意：设置返回按钮图片和返回按钮回调，必选是在播放后才写这些代码，放在playerView的懒加载中无效。
    //设置返回按钮图片
    if (_isInCell) {
        [_playerView.controlView.backBtn setImage:[UIImage imageNamed:XSHPlayerSrcName(@"ZFPlayer_close")] forState:UIControlStateNormal];
    }
    //返回按钮回调事件
    __weak typeof(self) weakSelf = self;
    _playerView.goBackBlock = ^(){
        if (!weakSelf.isInCell) {
            weakSelf.isInCell = YES;
            weakSelf.playerView.controlView.fullScreenBtn.selected = NO;
        }
        [weakSelf releasePlayerView];
        //调用这句话才能更新状态栏（控制显示、隐藏以及样式）
        [weakSelf setNeedsStatusBarAppearanceUpdate];
        //为下一次播放做准备
        _isInCell = YES;
    };
    _playerView.playCompletedBlock = ^(){
        if (!weakSelf.isInCell) {
            weakSelf.isInCell = YES;
            weakSelf.playerView.controlView.fullScreenBtn.selected = NO;
        }
        [weakSelf releasePlayerView];
        //调用这句话才能更新状态栏（控制显示、隐藏以及样式）
        [weakSelf setNeedsStatusBarAppearanceUpdate];
        //为下一次播放做准备
        _isInCell = YES;
    };
    _playerView.fullScreenBtnBlock = ^(UIButton *fullScreenBtn){
        if (fullScreenBtn.selected) {//转为非全屏状态
            _isInCell = YES;
            MPBViewControllerTableViewCell *currentCell = (MPBViewControllerTableViewCell *)[weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.currentIndexPath.row inSection:0]];
            [currentCell.cover_picImageView addSubview:weakSelf.playerView];
            [weakSelf toOrientation:UIInterfaceOrientationPortrait];
            fullScreenBtn.selected = NO;
        }else{//转为全屏状态
            _isInCell = NO;
            [[UIApplication sharedApplication].keyWindow addSubview:weakSelf.playerView];
            [weakSelf toOrientation:UIInterfaceOrientationLandscapeRight];
            [weakSelf.playerView.controlView.backBtn setImage:[UIImage imageNamed:XSHPlayerSrcName(@"ZFPlayer_close")] forState:UIControlStateNormal];
            fullScreenBtn.selected = YES;
        }
        //调用这句话才能更新状态栏（控制显示、隐藏以及样式）
        [weakSelf setNeedsStatusBarAppearanceUpdate];
    };
    XSHPlayerToolView *controlView = self.playerView.controlView;
    [controlView.activity startAnimating];
    
    
    [self.tableView reloadData];
}
-(void)startPlayVideo:(UIButton *)sender{
    
    MPModel *model = [MPModel mj_objectWithKeyValues:self.arrayItemModel[sender.tag]];
    
    [self ParsingVideoAddress:model.url Block:^(NSString *url){
       
        [self PlayVideo:sender VideoUrl:url];
        
    }];
    
    
    
    
    
}

- (void)releasePlayerView{
    [self.playerView pause];
    [self.playerView removeFromSuperview];
    [self.playerView.playerLayer removeFromSuperlayer];
    //    self.playerView = nil;
}
#pragma mark -控制状态栏显示和隐藏
- (BOOL)prefersStatusBarHidden{
    if (_isInCell) {
        return NO;
    }else{
        return YES;
    }
    return NO;
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}



#pragma mark- 屏幕旋转相关
//点击进入,退出全屏,或者监测到屏幕旋转去调用的方法
-(void)toOrientation:(UIInterfaceOrientation)orientation{
    //根据要旋转的方向,使用Masonry重新修改限制
    if (orientation ==UIInterfaceOrientationPortrait) {//
        MPBViewControllerTableViewCell *currentCell = (MPBViewControllerTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndexPath.row inSection:0]];
        [_playerView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(currentCell.cover_picImageView).with.offset(0);
            make.left.equalTo(currentCell.cover_picImageView).with.offset(0);
            make.right.equalTo(currentCell.cover_picImageView).with.offset(0);
            make.height.equalTo(@(currentCell.cover_picImageView.frame.size.height));
        }];
    }else{
        [_playerView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@([UIScreen mainScreen].bounds.size.height));
            make.height.equalTo(@([UIScreen mainScreen].bounds.size.width));
            make.center.equalTo(_playerView.superview);
        }];
    }
    //获取旋转状态条需要的时间:
    [UIView beginAnimations:nil context:nil];
    //给你的播放视频的view视图设置旋转
    if (orientation ==UIInterfaceOrientationPortrait) {
        _playerView.transform = CGAffineTransformIdentity;
    }else{
        _playerView.transform = CGAffineTransformMakeRotation(-M_PI_2);
    }
    [UIView setAnimationDuration:1.0];
    //开始旋转
    [UIView commitAnimations];
}

#pragma mark - scrollView代理方法
//tableViewCell离开界面，视频消失
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        if(_playerView == nil){
            return;
        }
        if (_playerView.superview) {//播放的cell在当前屏幕可视区
            CGRect rectInTableView = [self.tableView rectForRowAtIndexPath:_currentIndexPath];
            CGRect rectInSuperview = [self.tableView convertRect:rectInTableView toView:[self.tableView superview]];
            
            if (rectInSuperview.origin.y<-self.currentCell.cover_picImageView.frame.size.height||rectInSuperview.origin.y>[UIScreen mainScreen].bounds.size.height-64-49) {//往上拖动
                if ([[UIApplication sharedApplication].keyWindow.subviews containsObject:_playerView]&&_isBottomVideo) {
                    _isBottomVideo = YES;
                }else{
                    //放到window，在底部显示
                    [self toBottomVideo];
                }
            }else{
                if ([self.currentCell.cover_picImageView.subviews containsObject:_playerView]) {
                    
                }else{
                    //回到原来的cell上
                    [self toCell];
//                    [NSObject cancelPreviousPerformRequestsWithTarget:self];
//                    [self performSelector:@selector(toCell) withObject:nil afterDelay:0.3];
                }
            }
        }
    }
    
}
//放到window，在底部显示
- (void)toBottomVideo{
    //放widow上
    [_playerView removeFromSuperview];
    
    _playerView.frame = CGRectMake(ScreenWidth + (100 * 16 / 9.0),ScreenHigh - 100 - 60, 100 * 16 / 9.0, 100);
    
    [UIView animateWithDuration:0.5f animations:^{
        [[UIApplication sharedApplication].keyWindow addSubview:_playerView];
        _playerView.playerLayerGravity = XSHPlayerLayerGravityResizeAspectFill;
        
        _playerView.frame = CGRectMake(ScreenWidth - 100 * 16 / 9.0 - 5,ScreenHigh - 100 - 60, 100 * 16 / 9.0, 100);
        _playerView.playerLayer.frame =  _playerView.bounds;
        [self.playerView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(100 * 16 / 9.0);
            make.trailing.mas_equalTo(-5);
            make.bottom.mas_equalTo(-self.tableView.contentInset.bottom-60);
            make.height.equalTo(@100);
        }];
    }completion:^(BOOL finished) {
        _isBottomVideo = YES;
        [[UIApplication sharedApplication].keyWindow bringSubviewToFront:_playerView];
        //隐藏控制层的top和bottom
        _playerView.controlView.topImageView.hidden = YES;
        _playerView.controlView.bottomImageView.hidden = YES;
    }];
}
//放到cell上播放
- (void)toCell{
    
    MPBViewControllerTableViewCell *currentCell = (MPBViewControllerTableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_currentIndexPath.row inSection:0]];
    
        //_playerView.transform = CGAffineTransformIdentity;
        _playerView.frame = currentCell.cover_picImageView.bounds;
        _playerView.playerLayer.frame =  _playerView.bounds;
        [currentCell.cover_picImageView addSubview:_playerView];
        [currentCell.cover_picImageView bringSubviewToFront:_playerView];
        [_playerView mas_remakeConstraints:^(MASConstraintMaker *make) {
            //make.edges.equalTo(_playerView).with.offset(0);
            make.edges.mas_equalTo(0);
            make.width.mas_equalTo(_playerView.frame.size.width);
            make.height.mas_equalTo(_playerView.frame.size.height);
        }];
  
        _isBottomVideo = NO;
        _playerView.playerLayerGravity = XSHPlayerLayerGravityResize;
        //显示控制层的top和bottom
        _playerView.controlView.topImageView.hidden = NO;
        _playerView.controlView.bottomImageView.hidden = NO;
    
}



@end
